package com.hequ.merchant.banner.util;

import android.content.Context;
import android.util.Log;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class PostUtil {
	public static String TAG = "POSTIMG";
	/**
	 * 上传文件至Server的方法
	 */
	static String end = "\r\n";
	static String twoHyphens = "--";
	static String boundary = "*****";

	public static void postImg(Context context, String urlPath,
			String filePath, HashMap<String, String> params) {

		{

			try {
				URL url = new URL(urlPath);
				HttpURLConnection con = (HttpURLConnection) url
						.openConnection();
				/* 允许Input、Output，不使用Cache */
				con.setDoInput(true);
				con.setDoOutput(true);
				con.setUseCaches(false);
				/* 设置传送的method=POST */
				con.setRequestMethod("POST");
				/* setRequestProperty */
				con.setRequestProperty("Connection", "Keep-Alive");
				con.setRequestProperty("Charset", "UTF-8");
				con.setRequestProperty("Content-Type",
						"multipart/form-data;boundary=" + boundary);
				con.setRequestProperty("AccessToken", "");

				/* 设置DataOutputStream */
				DataOutputStream ds = new DataOutputStream(
						con.getOutputStream());

				// 传参数
				// HashMap<String, String> params = new HashMap<String,
				// String>();
				// params.put("userId", "0123456789");
				writeStringParams(params, ds);

				// 传图片
				// String filePath = UserData.ALBUM_PATH + File.separator
				// + UserData.adnames[0] + ".png";
				HashMap<String, File> fileMap = new HashMap<String, File>();
				fileMap.put("img", new File(filePath));
				writeFileParams(fileMap, ds);

				// 添加结尾数据
				ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
				ds.writeBytes(end);
				ds.flush();

				/* 取得Response内容 */
				InputStream is = con.getInputStream();
				int ch;
				StringBuffer b = new StringBuffer();
				while ((ch = is.read()) != -1) {
					b.append((char) ch);
				}
				int reponseCode = con.getResponseCode();
				if (reponseCode == 200) {
					Log.d(TAG, "上传成功" + b.toString().trim());
					System.out.println("上传成功" + b.toString().trim());
				}
				ds.close();
			} catch (Exception e) {
				Log.d(TAG, "上传失败" + e);
				System.out.println("上传失败" + e);
			}
		}
	}

	// 普通字符串数据
	private static void writeStringParams(Map<String, String> params,
			DataOutputStream ds) throws Exception {
		Set<String> keySet = params.keySet();
		for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
			String name = it.next();
			Log.d("xxx", name);
			String value = params.get(name);
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; name=\"" + name
					+ "\"" + end);
			Log.d(TAG, "参数：      " + "Content-Disposition: form-data; name=\""
					+ name + "\"" + end);
			ds.writeBytes(end);
			ds.writeBytes(value);
			ds.writeBytes(end);
		}
	}

	// 文件数据
	private static void writeFileParams(Map<String, File> params,
			DataOutputStream ds) throws Exception {
		Set<String> keySet = params.keySet();
		for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
			String name = it.next();
			File value = params.get(name);
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; name=\"" + name
					+ "\"; filename=\"" + value.getName() + "\"" + end);
			Log.d(TAG, "文件：         "
					+ "Content-Disposition: form-data; name=\"" + name
					+ "\"; filename=\"" + value.getName() + "\"" + end);
			ds.writeBytes("Content-Type:image/jpeg" + end);
			ds.writeBytes("Content-Type: application/octet-stream; charset=utf-8"
					+ end);

			ds.writeBytes(end);
			// ds.write(getBytes(value));
			InputStream is = new FileInputStream(value);
			byte[] bytes = new byte[1024];
			int len = 0;
			while ((len = is.read(bytes)) != -1) {
				ds.write(bytes, 0, len);
			}
			is.close();
			ds.writeBytes(end);
		}
	}

}
